
import React, { Component } from 'react';
import { Button, Progress } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import sha256_digest from './../../utils/js-sha256';
import { getCsrfToken } from './../../utils/common';
import Utils from './../../utils/utils';
import baseURL from './../../config/baseurl';
import iconList from './../../config/suffixIcon';
import './index.less';
const $ = window.$;
const WebUploader = window.WebUploader;
let wuFormData = {
	id: "",
	key: "",
	chunkSize: 5 * 1024 * 1024,
	secret: ""
}
let newFiles = [];//文件数据
class IUpload extends Component {
	constructor(props) {
        super(props);
        this.state = {
			fileList: "",//遍历后的文件列表
			visible: false,
        };
        this.uploader = '';//存储创建后的WebUploader对象
		
	}
	componentDidMount() {
		this.createUploader();
    }
	
	//遍历数据
	renderFile = (arr) => {
		return arr.map((item, index) => {
			return <li id={item.id} key={index} className="file-item">
				<div className="item-left">
					<div className="img-wrap">
						<svg
							className="icon icon-upload"
							aria-hidden="true"
						>
						    <use xlinkHref={iconList[item.ext]}></use>
						</svg>
						{/*<img src={this.iconList(item.ext)} alt="" />*/}
					</div>
					<div className="filename-wrap">
						<span>{item.name}</span><br />
						<span>{(item.size)}</span>
					</div>
				</div>
				<div className="item-right">
					<span>{item.tip}</span>
					<Progress 
						type="circle"
						percent={item.percent}
						status={item.status}
						width={35}
					/>
				</div>
			</li>
		})
	}
	
	//改变状态
	changeStatus = (id, options) => {
		newFiles.forEach((item,index)=>{
			if(item.id === id){
				for(let val of options){
					newFiles[index][val.type] = val.txt;
				}
			}
		})
		let fileList = this.renderFile(newFiles);
		this.setState({fileList});
	}
	
	createUploader = () => {
		//配置可直接查看官网
        this.uploader = WebUploader.create({
			duplicate: true,//是否允许重复的图片
			auto: true, // 选完文件后，是否自动上传
			swf: './static/Uploader.swf', // swf文件路径
			server: baseURL + "/files/upload/local", // 文件接收服务端
			pick: { id: "#picker", multiple: true },//选择文件的按钮
			threads: 1,//上传并发数。允许同时最大上传进程数
			chunkRetry: 3,//普通断线重连次数
			prepareNextFile: true,
			chunked: true,//分片处理
			chunkSize: wuFormData.chunkSize,//每片5M
			formData: {
				CSRF: getCsrfToken()
			},
			fileSingleSizeLimit: 50 * 1024 * 1024 * 1024,//单个文件最大大小5G
			fileNumLimit:100000,//上传文件数量限制
			compress:false,//上传前不压缩
			withCredentials: true
        });
		
		//当文件被加入队列之前触发
        this.uploader.on('beforeFileQueued', (file) => {
			var reader = new FileReader();
			reader.readAsArrayBuffer(file.source.source);
			reader.onload = function(){
				if (file.size <= 64*1024) {
					wuFormData.secret =  sha256_digest(reader.result + reader.result + reader.result + file.size);
					return;
				}
				var start = reader.result.slice(0, 64*1024),
					middle = reader.result.slice(file.size/2-32*1024, 64*1024),
					end = reader.result.slice(-64*1024);
					
				wuFormData.secret =  sha256_digest(start+middle+end+file.size);
			};
			
			//计算指纹，比对指纹，若指纹相同，则不必加入队列，直接成功，秒传
			var data = {
				filename: file.name,
				size: file.size,
				type: file.type,
				lastModifiedDate: file.lastModifiedDate,
				pid: this.props.pid,
				CSRF: getCsrfToken()
			};
			$.ajax({
				type: "POST",
				url: baseURL + "/files/upload/before",
				data: data,
				dataType: "json",
				// async : false,
				crossDomain:true, //设置跨域为true
				xhrFields: {
					withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
				},
				success: data => {
					if(data.code === 0){
						wuFormData.id = data.result.id;
						wuFormData.key = data.result.key;
					}else{
						// this.changeStatus(file.id, [{"tip", data.msg}]);
					}
				}
			});
        });
		
		//当某个文件的分块在发送前触发
		this.uploader.on('uploadBeforeSend', (object, data, headers) => {
			data.filename = object.file.name;
			data.pid = this.props.pid;
			data.chunks = object.chunks;
			data.chunk = object.chunk || 0;
			data.size = object.end - object.start;
			data.totalsize = object.file.size;
			data.finger = wuFormData.secret;
			data.chunksize = wuFormData.chunkSize;
			data.id = wuFormData.id;
			data.key = wuFormData.key;
		});
		
		//当一批文件加入队列
		this.uploader.on('filesQueued', (files) => {
			newFiles = files.map(item => {
				return {id: item.id,
					name: item.name,
					size: Utils.mertic(item.size),
					tip: "文件准备中",
					percent: 0,
					ext: item.ext
				}
			})
			let fileList = this.renderFile(newFiles);
			this.setState({
				visible: true,
				fileList
			})
		})
		
		//当单文件上传开始
		this.uploader.on('uploadStart', (file) => {
			this.changeStatus(file.id, [{type:"tip", txt:"开始上传"},{type:"status",txt:"active"}]);
		})
		
		 //进度处理
		this.uploader.on('uploadProgress', (file, percentage) => {
			let percent = Math.round(percentage * 100);
			let active = "active"
			if(percent === 100){
				active = ""
			}
			this.changeStatus(file.id, [{type:"percent", txt:percent},{type:"status",txt:active}]);
		});
		
		//当单文件上传成功
		this.uploader.on('uploadSuccess', (file, response) => {
			if(response.code === 0){
				if (response.result && response.result.status === 2) {
					this.changeStatus(file.id, [{type:"tip", txt:"上传成功"},{type:"status",txt:""}]);
				}
			}else if(response.code === 132302){
				this.changeStatus(file.id, [{type:"tip", txt:"本地文件已存在"},{type:"status",txt:"exception"}]);
			}else if( response.code === 132602){
				this.changeStatus(file.id, [{type:"tip", txt:"不允许上传此类文件"},{type:"status",txt:"exception"}]);
			}else if(response.code === 1001){
				this.changeStatus(file.id, [{type:"tip", txt:response.msg},{type:"status",txt:"exception"}]);
			}else{
				this.changeStatus(file.id, [{type:"tip", txt:response.msg},{type:"status",txt:"exception"}]);
			}
		});
		
		//当单文件上传错误
		this.uploader.on('uploadError', (file, response) => {
			this.changeStatus(file.id, [{type:"tip", txt:response.msg},{type:"status",txt:"exception"}]);
		})
		
		//当所有文件上传结束时
		this.uploader.on('uploadFinished', (file) => {
			setTimeout(() => {
				this.props.refreshList();//刷新页面
			}, 1000);
		})
	}
		
	render(){
		return (
			<div>
				<div id={"picker"}>
					<Button type="primary" icon={<UploadOutlined />}>
						上传
					</Button>
				</div>
				{
					this.state.visible ?
						<div className="modal-content">
							<div className="modal-header">
								<span>上传文件</span>
								<span className="close closex" onClick={()=>this.setState({visible: false})}>X</span>
							</div>
							<div className="modal-body">
								<ul className="filelist-wrap">
									{ this.state.fileList }
								</ul>
							</div>
						</div>
						:""
				}
			</div>
		)
	}
}

export default IUpload;